package com.yjtc.cbg.commonutildemo.observable;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;

import java.lang.ref.WeakReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by chenboge on 2017/3/1.
 * <p>
 * 获取新收到短信验证码，自动填充到app
 */
public class SmsObserver extends ContentObserver {
    /**
     * Creates a content observer.
     *
     * @param handler The handler to run {@link #onChange} on, or null if none.
     * <p>
     * 有关短信的uri
     * <p>
     * content://sms/inbox    收件箱
     * <p>
     * content://sms/sent      已发送
     * <p>
     * content://sms/draft    草稿
     * <p>
     * content://sms/outbox    发件箱  (正在发送的信息)
     * <p>
     * content://sms/failed    发送失败
     * <p>
     * content://sms/queued    待发送列表  (比如开启飞行模式后，该短信就在待发送列表里)
     */

    public static final String SMS_URI_INBOX = "content://sms/inbox";

    private WeakReference<Activity> activity = null;

    private String smsContent = "";

    private SmsListener listener;

    //要获取的验证码发送方名称
    private String SmsBody = "艺匠";

    public SmsObserver(Handler handler, WeakReference<Activity> wActivity, SmsListener listener) {
        super(handler);
        this.listener = listener;
        this.activity = wActivity;
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Cursor cursor = null;
        // 读取收件箱中含有某关键词的短信
        ContentResolver contentResolver = activity.get().getContentResolver();
        cursor = contentResolver.query(Uri.parse(SMS_URI_INBOX), new String[]{
                        "_id", "address", "body", "read"}, "body like ? and read=?",
                new String[]{"%"+SmsBody+"%", "0"}, "date desc");//0未读
        if (cursor != null) {
            cursor.moveToFirst();
            if (cursor.moveToFirst()) {
                String smsbody = cursor
                        .getString(cursor.getColumnIndex("body"));
                String regEx = "[^0-9]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(smsbody.toString());
                smsContent = m.replaceAll("").trim().toString();
                if (!TextUtils.isEmpty(smsContent)) {
                    listener.onResult(smsContent);
                }

            }
        }
    }


    /*
    * 短信回调接口
    */
    public interface SmsListener {
        /**
         * 接受sms状态
         *
         * @Title: onResult
         */
        void onResult(String smsContent);
    }
}
